package component.entry{


    import flash.display.DisplayObject;
    import flash.events.*;
    import flash.net.*;
    
    import flexunit.framework.*;
    
    import mx.containers.*;
    import mx.controls.*;
    import mx.events.ItemClickEvent;
    
    import org.pubflex.AssetManager;
    import org.pubflex.SocketURLLoader;
        	
    public class EntryFormBase extends VBox{
        namespace XML_NS = "http://www.w3.org/XML/1998/namespace";
        namespace ATOM = "http://www.w3.org/2005/Atom"
        namespace APP = "http://www.w3.org/2007/app";                
        namespace ATOM_NS = "http://purl.org/atom/ns#"
        
        public static const DELETE_COMPLETE:String = "deleteComplete";
        
        [Bindable] public var entryList:List;    
        [Bindable] public var entryTitle:String = "Title [***]";    
        [Bindable] public var edited:String;            
        [Bindable] public var authorList:List;    
        [Bindable] public var entrySummary:TextArea;
        [Bindable] public var entryContent:DisplayObject;
        [Bindable] public var collectionComboBox:ComboBox;               
//        [Bindable] public var formControlBar:ControlBar;
        [Bindable] public var baseURI:String;
        [Bindable] public var entryXml:XML;
        [Bindable] public var entryButtonBar:ButtonBar;
       	[Bindable] public var urlLoader:SocketURLLoader = new SocketURLLoader();              		
        [Bindable] public var content:FormItem;

        public function EntryFormBase(){
            super();
        }
        

        public function loadXml(entryXML:XML, collectionXML:XML):void{
            trace("EntryFormBase.loadEntryIntoForm() ");
            this.entryXml = entryXML;
            use namespace ATOM; 
            use namespace ATOM_NS;             
            use namespace APP; 
            use namespace XML_NS;
                                                    
                                                    
            entryTitle = entryXML.title.text();
            edited = entryXML.edited;
            // COLLECTION
            var coll:Array = new Array();
            var acceptType:XML; 
            var label:LinkButton;
            if(collectionXML != null){
                for each(acceptType in collectionXML.accept){
                    label = new LinkButton();
                    label.label = acceptType.text();                
                    label.data = acceptType;
                    label.data = acceptType;
                    trace(acceptType.text());
                    coll.push(label);
                }
            }
           //collectionComboBox.dataProvider = coll; 
                        
            var authors:XMLList = entryXML.author;
            trace("authors : " + authors);
            var author:XML;
       	    var authorListArray:Array = new Array();

            for each(author in authors) {
                trace("author : " + author.name.text());
                var button:LinkButton = new LinkButton();
                button.label = author.name.text();
                button.data = author;
                authorListArray.push(button);
            }

           authorList.dataProvider = authorListArray;                       
                    
           // SUMMARY
           trace("Summary : " + entryXML.summary.text());
    
           var summaryString:String = new String(entryXML.summary.text());
           var betterString:String = summaryString.split("\n").join(""); 

           
           trace("Summary : " + betterString);
                    
           // CONTENT                    
          trace("Content Type : " + entryXML.content.@type );
          //entryEditor.entryForm.content.text = entryLink.entryXML.content.text().split("\n").join("");

          // XXX Do a better job a determining the media type
          if(entryXML.content.@type == "text/html" || entryXML.content.@type == "html"){
             entryContent = new HTML();
             HTML(entryContent).htmlText = entryXML.content.text();
             this.content.initialize();
             this.content.addChild(entryContent);
          }else{
            entryContent = new TextArea();
            TextArea(entryContent).text = entryXML.content.text();
            this.content.addChild(entryContent);
          }
          //entryContent.htmlText = entryXML.content.text();            	                                                                                                                                    
          trace("***************************");
          trace(entryXML.content.text());  
          addLinkRelations();
                                              
        }            
   
        public function addLinkRelations():void{
           use namespace ATOM;
            var linkListArray:Array = new Array();
            var link:XML;                   
            for each (link in entryXml.link){         
                var linkButton:LinkButton = new LinkButton();            
                                    
                if(link.@rel == "edit"){
                      
                  var o:Object = new Object();
                  o.relatedObject = link
                  o.icon = AssetManager.ICON_BRICK_EDIT;
                  o.label = "UPDATE";
                  linkListArray.push(o);    
            
                  var d:Object = new Object();
                  d.relatedObject = link
                  d.label = "DELETE";
                  d.icon = AssetManager.ICON_BRICK_DELETE;
                  linkListArray.push(d); 
               } 
           }                                       
            trace("Link List : " + linkListArray); 

            entryButtonBar.dataProvider = linkListArray;                     
        }
        
        public function traceEvent(e:Event):void{
            trace("traceEvent() called")
            trace(e);
            trace("propagating event");
            dispatchEvent(e);
        }
        
        public function handleDeleteRequest(e:Event):void{

            namespace atom = "http://www.w3.org/2005/Atom"
            use namespace atom;   
            
            trace(e);
            trace(e.currentTarget);
            var deleteButton:LinkButton = e.currentTarget as LinkButton; 
            var xml:XML = deleteButton.data as XML;
            var path:String = xml.@href;
            trace(this.baseURI + path);
            
           var request:URLRequest = new URLRequest();
            request.url = this.baseURI + path;
            //var authHeader:URLRequestHeader = new URLRequestHeader("Authorization","Basic " + your_credentials);
            //request.requestHeaders.push(authHeader);
            //Security.loadPolicyFile('"http://yourhost.com/crossdomain.xml');
            urlLoader.showBusyCursor = true;
            urlLoader.requestTimeout = 10;
            urlLoader.method = "DELETE"

            urlLoader.addEventListener(Event.COMPLETE, handleCompletionEvent);
			urlLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, handleStatusEvent);
			urlLoader.addEventListener(IOErrorEvent.IO_ERROR, traceEvent);
			//loader.addEventListener(ProgressEvent.PROGRESS, traceEvent);
			urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, traceEvent);
   		    		 
            urlLoader.load(request);

        }
    
        public function clearForm():void{
            //authorList.dataProvider = null;
            //entryContent.text = null; 
            //entrySummary.text = null;
            //this.parent.removeChild(this);

        }
        public function handleCompletionEvent(e:Event):void{
            trace("handleCompletionEvent() called")
            trace(e);
            trace("Reponse Headers : " + urlLoader.responseHeaders);
            trace("Propagating event");
            clearForm();
            dispatchEvent(new Event(EntryFormBase.DELETE_COMPLETE,true,false));
            
        }
    
        private function handleStatusEvent(event:HTTPStatusEvent, token:Object=null):void {
            trace("Event Status : " + event.status);  
            trace("Token : " + token);  
            var status:int = event.status;                       
            trace(event.responseHeaders);          
            dispatchEvent(event);
        }
        
        public function handleButtonBarClick(event:ItemClickEvent){
            use namespace ATOM;        
            use namespace XML_NS;



            trace(entryXml);
            trace ( entryXml.link) ;  
            trace ( entryXml.link.@rel ) ;
            trace ( entryXml.*.@rel ) ;
            var o:Object = entryXml.link.(@rel == "edit");
            trace ( o) ;

            var l:XML; 
            var linkPath:String;
            for each (l in entryXml.link){
                if(l.@rel == "edit"){
                    trace("FINALLY");
                    trace(l.@href); 
                    linkPath = l.@href;
                }
            }
            
            var path:String = entryXml.@XML_NS::base + linkPath;
            
            var request:URLRequest = new URLRequest();
            request.url = path;
            //var authHeader:URLRequestHeader = new URLRequestHeader("Authorization","Basic " + your_credentials);
            //request.requestHeaders.push(authHeader);
            //Security.loadPolicyFile('"http://yourhost.com/crossdomain.xml');
            urlLoader.showBusyCursor = true;
            urlLoader.requestTimeout = 10;
            urlLoader.method = "DELETE"

         
            trace("--------------------------------------------------------------------");
            trace("PATH: " + request.url); 
            trace("HTTP method : " + "DELETE");
        
            
            urlLoader.addEventListener(Event.COMPLETE, handleCompletionEvent);
			urlLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, handleStatusEvent);
			urlLoader.addEventListener(IOErrorEvent.IO_ERROR, traceEvent);
			//loader.addEventListener(ProgressEvent.PROGRESS, traceEvent);
			urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, traceEvent);
   		    		 
            urlLoader.load(request);
        }
    }
}